package com.rad.ip.exporter;

import com.rad.base.model.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Date:  2018/5/21
 * Time:  16:58
 * Email: siy@hmgsoft.com
 * Created by siy
 */
@Component
public class IpQuartz {
    private Logger logger = LoggerFactory.getLogger(IpQuartz.class);
    @Value("${ip-discovery.server}")
    private String serverUrl;
    @Value("${ip-discovery.id}")
    private String serviceId;

    @Scheduled(cron = "0 0/1 * * * ?") // 每分钟执行一次
    public void work(){
        logger.info("发起ip报数{}",new Date());
        HttpHeaders headers = new HttpHeaders();
        RestTemplate template = new RestTemplate();
        //  请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //  封装参数，千万不要替换为Map与HashMap，否则参数无法传递
        MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
        params.add("serviceId",serviceId);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
        //  执行HTTP请求
        ResponseEntity<Result> response = template.exchange(serverUrl, HttpMethod.POST, requestEntity, Result.class);
        //  输出结果
        Result body = response.getBody();
        logger.info("请求结果：{}",body);
    }


//    @Scheduled(fixedRate = 5000)//每5秒执行一次
//    public void play() throws Exception {
//        System.out.println("执行Quartz定时器任务："+new Date());
//    }
//
//
//
//    @Scheduled(cron = "0/2 * * * * ?") //每2秒执行一次
//    public void doSomething() throws Exception {
//        System.out.println("每2秒执行一个的定时任务："+new Date());
//    }
//
//
//    @Scheduled(cron = "0 0 0/1 * * ? ") // 每一小时执行一次
//    public void goWork() throws Exception {
//        System.out.println("每一小时执行一次的定时任务："+new Date());
//    }
}
